package com.example.usbfileutils;

import android.icu.util.Output;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class UsbFileUtils {

    public static void copyFileToUsb(File sourceFile, List<String> usbPaths) {

        if (sourceFile.exists() && usbPaths.size() > 0) {
            try {
                FileInputStream fis = new FileInputStream(sourceFile);
                for (String usbPath : usbPaths) {
                    File usbDir = new File(usbPath);
                    if (usbDir.exists() && usbDir.canWrite()) {
                        File destinationFile = new File(usbDir, sourceFile.getName());
                        FileOutputStream fos = new FileOutputStream(destinationFile);
                        copyStream(fis, fos);
                        fos.close();
                    }
                }
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
    }
}
